$(document).ready(function() {
	$("input.phone").mask("(999) 999-9999");
	$.mockjax({
		url: "emails.action",
		response: function(settings) {
			var email = settings.data.email,
				emails = ["glen@marketo.com", "george@bush.gov", "me@god.com", "aboutface@cooper.com", "steam@valve.com", "bill@gates.com"];
			this.responseText = "true";
			if ( $.inArray( email, emails ) !== -1 ) {
				this.responseText = "That's already taken.";
			}
		},
		responseTime: 500
	});

	$.mockjax({
		url: "users.action",
		response: function(settings) {
			var user = settings.data.username,
				users = ["asdf", "Peter", "Peter2", "George"];
			this.responseText = "true";
			if ( $.inArray( user, users ) !== -1 ) {
				this.responseText = "false";
			}
		},
		responseTime: 500
	});

	// validate for EditUserProfile page
	var validator = $("#profileForm").validate({
		rules: {
			departmentDesc: "required",
			departmentId: "required",
			approval: "required",
			phone:{
				required: true,
				minlength: 10,
				number: true,
			},
			memail: "required",
			VPName: "required",
			reason: "required",
			firstname: "required",
			mIn:"required",
			lastname: "required",
			username: {
				required: true,
				minlength: 2,
				remote: "users.action"
			},
			password: {
				required: true,
				minlength: 5
			},
			password_confirm: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true,
				remote: "emails.action"
			},
			dateformat: "required",
			terms: "required"
		},
		messages: {
			departmentDesc: "Enter your department descript",
			departmentId: "Enter your department id",
			phone: "Enter you a valid phone number ",
			memail: "Please enter an email address",
			VPName: "Enter a VP Name",
			reason: "Enter a reason for access",
			firstname: "Enter your firstname",
			mIn:"Enter you Middle Name Initial",
			lastname: "Enter your lastname",
			approval: "Manager Approval cannot be left blank",
			username: {
				required: "Enter a username",
				minlength: jQuery.format("Enter at least {0} characters"),
				remote: jQuery.format("{0} is already in use")
			},
			password: {
				required: "Provide a password",
				rangelength: jQuery.format("Enter at least {0} characters")
			},
			password_confirm: {
				required: "Repeat your password",
				minlength: jQuery.format("Enter at least {0} characters"),
				equalTo: "Enter the same password as above"
			},
			email: {
				required: "Please enter an email address",
				minlength: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			dateformat: "Choose your preferred dateformat",
			terms: " "
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			
			if (typeof(microstrategy) != 'undefined') {
				var session = String(microstrategy.sessionState);
			}
			taskUrl = "./taskProc?taskId=UserProfileService&taskEnv=xhr&taskContentType=json&session=" + String(session) + "&rand=" + (new Date()).getTime();
			console.log("taskUrl: " + taskUrl );
			$(form).ajaxSubmit({
				type : "post",
				url : taskUrl,
				dataType : 'text',
				// beforeSubmit: showRequest,
				success : function(data) {
					//console.log("data: " + data);
					eval("var responseContent=" + data);
					if (responseContent["status"] == uam.Utils.responseCode.OK) {
						location.href = "../plugins/UAM/jsp/MCS-User-Profile_Registration_new.jsp";
					};					
				},
				error : function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				}
				
		    });
			return false;
	        
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			//alert("pass"+label);
			label.html("&nbsp;").addClass("checked");
		},
		highlight: function(element, errorClass) {
			$(element).parent().next().find("." + errorClass).removeClass("checked");
		}
	});
	
	/*=================== validate for PreApprovedRegistration page =================*/
	var validator = $("#preApprovedRegForm").validate({
		rules: {
			predepartmentDesc: "required",
			predepartmentId: "required",
			approval: "required",
			prephone:{
				required: true,
				minlength: 10,
				number: true,
			},
			prememail: "required",
			preVPName: "required",
			prereason: "required",
			prefirstname: "required",
			premIn:"required",
			prelastname: "required",
			username: {
				required: true,
				minlength: 2,
				remote: "users.action"
			},
			password: {
				required: true,
				minlength: 5
			},
			password_confirm: {
				required: true,
				minlength: 5,
				equalTo: "#password"
			},
			preemail: {
				required: true,
				email: true,
				remote: "emails.action"
			},
			dateformat: "required",
			terms: "required"
		},
		messages: {
			predepartmentDesc: "Enter your department descript",
			predepartmentId: "Enter your department id",
			prephone: "Enter you a valid phone number ",
			prememail: "Please enter an email address",
			preVPName: "Enter a VP Name",
			prereason: "Enter a reason for access",
			prefirstname: "Enter your firstname",
			premIn:"Enter you Middle Name Initial",
			prelastname: "Enter your lastname",
			approval: "Manager Approval cannot be left blank",
			username: {
				required: "Enter a username",
				minlength: jQuery.format("Enter at least {0} characters"),
				remote: jQuery.format("{0} is already in use")
			},
			password: {
				required: "Provide a password",
				rangelength: jQuery.format("Enter at least {0} characters")
			},
			password_confirm: {
				required: "Repeat your password",
				minlength: jQuery.format("Enter at least {0} characters"),
				equalTo: "Enter the same password as above"
			},
			preemail: {
				required: "Please enter an email address",
				minlength: "Please enter a valid email address",
				remote: jQuery.format("{0} is already in use")
			},
			dateformat: "Choose your preferred dateformat",
			terms: " "
		},
		// the errorPlacement has to take the table layout into account
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo( element.parent().next().next() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.next() );
			else
				error.appendTo( element.parent().next() );
		},
		// specifying a submitHandler prevents the default submit, good for the demo
		submitHandler: function(form) {
			//console.log("submitted!");
			//console.log(form);
			if (typeof(microstrategy) != 'undefined') {
				var session = String(microstrategy.sessionState);
			}
			taskUrl = "./taskProc?taskId=UserProfileService&taskEnv=xhr&taskContentType=json&session=" + String(session) + "&rand=" + (new Date()).getTime();
			//console.log("taskUrl: " + taskUrl );
			$(form).ajaxSubmit({
				type : "post",
				url : taskUrl,
				dataType : 'json',
				// beforeSubmit: showRequest,
				success : function(data) {
					console.log("data: " + data);
					if (data["status"] == 200/*uam.Utils.responseCode.OK*/) {
						location.href = "../plugins/UAM/jsp/Exception-Access_Confirmation.jsp";
					};					
				},
				error : function (XMLHttpRequest, textStatus, errorThrown) {
					console.log("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
				}
				
		    });
			return false;
	        
		},
		// set this class to error-labels to indicate valid fields
		success: function(label) {
			// set &nbsp; as text for IE
			//alert("pass"+label);
			label.html("&nbsp;").addClass("checked");
		},
		highlight: function(element, errorClass) {
			$(element).parent().next().find("." + errorClass).removeClass("checked");
		}
	});

	// propose username by combining first- and lastname
	$("#username").focus(function() {
		var firstname = $("#firstname").val();
		var lastname = $("#lastname").val();
		if(firstname && lastname && !this.value) {
			this.value = (firstname + "." + lastname).toLowerCase();
		}
	});
});